package center

import (
	"github.com/astaxie/beego/orm"
	"time"
)

type Action struct {
	Id         int64     `orm:"column(id);auto"`
	Pid        int64     `orm:"column(pid);"`
	Controller string    `orm:"column(controller);size(50)"`
	Action     string    `orm:"column(action);size(50)"`
	Des        string    `orm:"column(des);size(150);null"`
	Create     time.Time `orm:"column(create);auto_now_add;type(datetime)"`
	Updated    time.Time `orm:"column(updated);auto_now;type(datetime)"`
	Count      int       `orm:"colum(count);"`
	Group      string    `orm:"colum(group);size(50)"`
	Ispublic   bool      `orm:"column(ispublc);default(true)"`
	Actiontype int       `orm:"column(Actiontype);default(1)"`
}

func (t *Action) TableName() string {
	return "action"
}

func init() {
	//orm.RegisterModelWithPrefix("uc_", new(Action))
	orm.RegisterModel(new(Action))
}

func CheckAction(controller string, action string, group string) (id int64, err error) {
	id, err = FindAction(controller, action, group)
	if err == nil {
		IncAction(id)
	} else {
		id, err = AddAction(controller, action, group)
	}
	return
}

func AddAction(controller string, action string, group string) (id int64, err error) {
	o := orm.NewOrm()
	a := Action{Controller: controller, Action: action, Count: 1, Group: group}
	id, err = o.Insert(&a)
	return
}

func FindAction(controller string, action string, group string) (id int64, err error) {
	o := orm.NewOrm()
	t := Action{}
	err = o.QueryTable(&t).Filter("Controller", controller).Filter("Action", action).Filter("Group", group).One(&t)
	if err == nil {
		id = t.Id
	}
	return
}

func GetAction(id int64) (a Action, err error) {
	o := orm.NewOrm()
	a.Id = id
	err = o.Read(&a)
	return
}

func IncAction(id int64) {
	o := orm.NewOrm()
	t := Action{Id: id}
	if o.Read(&t) == nil {
		t.Count = t.Count + 1
		o.Update(&t)
	}
}
